package com.ca.demo.common.base;

import com.ca.demo.common.page.PageRequest;
import com.ca.demo.config.security.SecurityUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * @Author XieLei
 * @Date 2017/6/22 14:12
 */
public abstract class BaseServiceImpl<T extends BaseEntity<ID>, ID extends Serializable> implements BaseService<T, ID> {

    private BaseMapper<T, ID> baseMapper;

    @Autowired
    protected void setBaseMapper(BaseMapper<T, ID> baseMapper) {
        this.baseMapper = baseMapper;
    }

    protected void doBeforeSave(T entity) {
        entity.setId(entity.newId());
        entity.setCreateAt(new Date());
        entity.setCreateBy(SecurityUtil.getCurrentUser().getUsername());
    }

    protected void doBeforeUpdate(T entity) {
        entity.setUpdateAt(new Date());
        entity.setUpdateBy(SecurityUtil.getCurrentUser().getUsername());
    }

    @Override
    public T findOne(ID id) {
        return baseMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo<T> findByPage(T example, PageRequest pageRequest) {
        if (pageRequest != null) {
            PageHelper.startPage(pageRequest.getPageNo(), pageRequest.getPageSize());
        }
        List<T> list = baseMapper.select(example);

        return new PageInfo<>(list);
    }

    @Override
    public T save(T entity) {
        doBeforeSave(entity);
        int count = baseMapper.insertSelective(entity);
        if (count > 0) {
            return entity;
        }
        return null;
    }

    @Override
    public T update(T entity) {
        doBeforeUpdate(entity);
        int count = baseMapper.updateByPrimaryKeySelective(entity);
        if (count > 0) {
            return entity;
        }
        return null;
    }

    @Override
    public List<T> batchSave(List<T> entities) {
        for (T entity : entities) {
            doBeforeSave(entity);
        }
        int count = baseMapper.insertList(entities);
        if (count > 0) {
            return entities;
        }
        return null;
    }

    @Override
    public List<T> findAll() {
        return baseMapper.selectAll();
    }
}
